package utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

    public static String nullToEmpty(Object string){
        return string == null ?  "" : string.toString();
    }

    public static boolean isNotEmpty(String string) {
        return string != null && !string.isEmpty();
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static String removeStartEnd(String string, String startString,
                                        String endString) {
        string = removeStart(string, startString);
        string = removeEnd(string, endString);
        return string;
    }

    public static String removeStart(String str, String remove) {
        if (isEmpty(str) || isEmpty(remove)) {
            return str;
        }
        if (str.startsWith(remove)){
            return str.substring(remove.length());
        }
        return str;
    }

    public static String removeEnd(String str, String remove) {
        if (isEmpty(str) || isEmpty(remove)) {
            return str;
        }
        if (str.endsWith(remove)) {
            return str.substring(0, str.length() - remove.length());
        }
        return str;
    }

    /**
     * 格式化, 将字符串"{0}12{3}"中的"{0}", "{3}"替换成其他值.
     *
     * @param string
     * @param replaceStrings
     * @return
     */
    public static String formatByNumber(String string, Object... replaceStrings) {
        String regex = "\\{\\d\\}";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(string);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String indexString = matcher.group();
            indexString = removeStartEnd(indexString, "{", "}");
            int i = Integer.parseInt(indexString);
            if (i < replaceStrings.length) {
                String replacement = String.valueOf(replaceStrings[i]);
                matcher.appendReplacement(sb,
                        Matcher.quoteReplacement(replacement));
            }
        }
        matcher.appendTail(sb);
        return sb.toString();

    }


}
